<template>
  <view class="container">
    <u-loading-page :loading="loading > 0" loading-text="正在上传中..." class="u_loading_page"></u-loading-page>
    <view class="upload_info">
      <view class="upload_type">
        <text>课程名称:</text>
        <u--input :disabled="detail" placeholder="请输入课程名称" clearable v-model="course.folderName" @blur="handleBlur"></u--input>
      </view>
      <view class="upload_type">
        <text>作者名称:</text>
        <u--input :disabled="detail" placeholder="请输入作者名称" clearable v-model="course.author"></u--input>
      </view>
      <view class="upload_type upload_type_introduction">
        <text>课程简介:</text>
        <u--textarea :disabled="detail" v-model="course.introduction" placeholder="请输入课程简介" count></u--textarea>
      </view>
      <view class="video_model">
        <view class="video_model_title"><image src="../../static/images/fileManage/file_manage_tree.svg"></image>视频组菜单：</view>
        <Tree v-if="tableData && tableData.length > 0" ref="tree" :course="course" :range="tableData" :rangeKey="rangeKey" :idKey="idKey" :title="title" :isEdit="id ? true : false" :selectParent="selectParent" :multiple="multiple" :foldAll="flod" @confirm="treeConfirm" @editName="editNameFn" @del="delFn" @handleDel="handleDel" @handleFileInfo="handleFileInfo" @uploadVideo="uploadVideo" @uploadVideofile="uploadVideofile" @optionTreeFn="optionTreeFn" @handleUpdate="handleUpdate" :methods="methods" @handlePlayer="handlePlayer" @update:loading="handleLoading"/>
      </view>
      <view class="bottom" v-if="!id">
        <!--        <u-button text="清空" @click="emptyFn"></u-button>-->
        <u-button text="取消" @click="closeFn"></u-button>
        <u-button type="primary" text="确定" @click="sureFn"></u-button>
        <!-- <u-button type="primary" text="更新" v-else @click="sureFn"></u-button> -->
      </view>
    </view>
    <!-- 文件更新 -->
    <u-popup mode="bottom" :show="updateShow" :round="10">
      <view class="container-update">
        <view class="info_item">
          <view class="info_item_label">专业类型：</view>
          <view class="info_item_content">
            <!-- {{updateData.professionName}} -->
            <uni-data-select disabled v-model="updateData.profession" :localdata="majorTypeList"></uni-data-select>
          </view>
        </view>
        <view class="info_item">
          <view class="info_item_label">文件类型：</view>
          <view class="info_item_content">
            <!-- {{updateData.fileTypeName}} -->
            <uni-data-select disabled v-model="updateData.fileType" :localdata="fileTypeList"></uni-data-select>
          </view>
        </view>
        <view class="info_item">
          <view class="info_item_label">文件名称：</view>
          <view class="info_item_content">
            <!-- {{updateData.fileName}} -->
            <uni-easyinput v-model="updateData.fileName" placeholder="请输入文件名称"></uni-easyinput>
          </view>
        </view>
        <!-- <view class="info_item">
          <view class="info_item_label">作者姓名：</view>
          <view class="info_item_content">
            <uni-easyinput v-model="updateData.author" placeholder="请输入作者姓名"></uni-easyinput>
          </view>
        </view> -->

        <view class="info_item">
          <view class="info_item_label">上传文件：</view>
          <view class="info_item_content">
            <u-button @click="handleUpdate1" type="primary">上传</u-button>
          </view>
        </view>
        <view class="info_item">
          <view class="info_item_label"></view>
          <view class="info_item_content">

            <text class="name">{{ updateProcessList.fileName }}</text>
          </view>
        </view>

        <view class="confrim-btn">
          <u-button text="取消" @click="updateShow = false"></u-button>
          <!-- <u-button @click="handleUpdateData" type="primary">上传</u-button> -->
          <u-button type="primary" @click="updateConfirm">确定</u-button>
        </view>
      </view>
    </u-popup>
    <u-modal title="更新" content="原文件已入库,如需更新,需对原文件进行升版" showCancelButton :show="updateModel" @cancel="closeModel" @confirm="confirm" ref="uModal" :asyncClose="true"> </u-modal>
    <!-- 进度条组件 -->
    <div v-if="progressVisible" class="progress-mask">
        <div class="progress-content">
            <!-- 圆形进度条 -->
            <div class="circle-progress-container">
                <div class="circle-progress">
                    <div class="progress-inner">
                        <uni-icons type="spinner" size="40" color="#007AFF" class="loading-icon"></uni-icons>
                        <div class="progress-text">{{ progress }}%</div>
                    </div>
                </div>
            </div>
            <!-- 上传信息 -->
            <div class="upload-info">
                <div class="upload-text">正在上传中...</div>
                <div class="file-name">{{ currentFileName || '准备上传文件' }}</div>
            </div>
        </div>
    </div>
  </view>
</template>

<script>
import config from "@/config";
import Tree from "@/components/tree/tree.vue";
const baseUrl = config.baseUrl;
import uploadView from "../uploadView";
export default {
  components: {
    Tree,
    uploadView
  },
  data() {
    return {
      loading: 0,
      updateModel: false,
      course: {
        folderName: "",
        author: "",
        introduction: "",
        fileType: "",
        profession: "",
      },
      timer: null,
      id: "",
      // 选中的结果
      result: null,
      tableData: [],
      rangeKey: "chapterName",

      // 指定 Object 中 key 的值作为单条数据的唯一id
      // 跟上面的类似,一个道理，只不过这个是标识的唯一id键名
      idKey: "id",

      // 是否多选(默认单选)
      multiple: false,

      // 是否可以选父级(默认不可选)
      selectParent: false,

      // 折叠时关闭所有已经打开的子集 再次打开时需要一级一级打开
      // 默认不关闭已打开的子集
      flod: false,

      // 标题
      title: "这是标题",
      token: "",
      detail: false,
      methods: "edit",
      isUpdate: false,
      updateStatus:true,
      updateShow: false,
      updateData: {},
      fileTypeList: [],
      majorTypeList: [],
      processList: [],
      updateProcessList: {},
      id: "",
      isUpload: false,
      uploadFileId: '',
      progressVisible: false,
      currentFileName: '',
      progress: 0
    };
  },
  mounted() {},
  onLoad: function (option) {
    const uploadForm = JSON.parse(decodeURIComponent(option.uploadForm));
    this.detail = option.detail == "true" ? true : false;
    this.course.fileType = uploadForm.fileType;
    this.course.profession = uploadForm.profession;
    this.id = uploadForm.id;
    this.token = uni.getStorageSync("token");
    this.methods = uploadForm.methods;
    if (this.course && this.id) {
      this.getInfo();
    }
    this.fileTypeListFn();
    this.majorTypeListFn();
  },
  watch: {
    "course.folderName"(newVal, oldVal) {
      if (newVal != oldVal) {
        if (this.tableData.length === 0) {
          this.tableData.push({
            chapterName: newVal,
            // id: Date.now(),
            chapter: Date.now(),
            parentId: null,
            level: 1,
          });
        } else {
          this.tableData.map((item) => {
            if (item.parentId === null) {
              this.$set(item, "chapterName", newVal);
            }
          });
        }
        // this.$refs.tree._initTree(this.tableData)
      }
    },
    course: {
      handler(newVal, oldVal) {
        console.log("看看这个是否更新", newVal, oldVal, Object.keys(newVal) == Object.keys(oldVal));

        // return
        if (Object.keys(newVal) != Object.keys(oldVal)) {
          clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            if (this.id && this.updateStatus) {
              this.sureFn();
            }else{
              this.updateStatus = true;
            }
          }, 1000);
        }
      },
      // immediate:true,
      deep: true,
    },
  },
  onUnload() {
  },
  onShow() {},
  methods: {
    handleLoading(isLoading) {
      return isLoading ? this.loading++ : this.loading--;
    },
    handleBlur() {
      if (this.course.folderName) {
        this.$refs.tree._initTree(this.tableData);
      }
    },
    // tree 操作更新需要重新提交数据方法
    optionTreeFn() {
      clearTimeout(this.timer);
      console.log(this.tableData, "更新操作");
      this.timer = setTimeout(() => {
        if (this.id) {
          this.sureFn();
        }
      }, 1000);
    },
    //文件字典
    fileTypeListFn() {
      this.$request({
        url: "/dict/file/list",
        method: "get",
        params: {},
      }).then(({ data }) => {
        data.data.forEach((item) => {
          this.fileTypeList.push({
            value: item.id,
            text: item.name,
            dictType: item.dictType,
            dictCode: item.dictCode,
          });
        });
      });
    },
    //专业字典
    majorTypeListFn() {
      this.$request({
        url: "/dict/major/list",
        method: "GET",
        params: {},
      }).then(({ data }) => {
        data.data.forEach((item) => {
          this.majorTypeList.push({
            value: item.id,
            text: item.name,
            dictCode: item.dictCode,
          });
        });
      });
    },
    getInfo() {
      let that = this;
      that
        .$request({
          url: "/knowledgeFile/video/detail",
          method: "get",
          params: {
            id: that.id,
          },
        })
        .then(({ data }) => {
          that.course = data.course;
          that.tableData[0] = data.video;
          this.$forceUpdate();
          this.$refs.tree._initTree(this.tableData);
        });
    },
    getFiles(list) {
      console.log("父级附件列表", list);
      this.updateProcessList = list;
    },

    treeConfirm(addItem, parentId) {
      console.log("看看这里的数据", this.tableData, addItem, parentId);
      // return
      // for (let item of this.tableData) {
      //   if (item.id === parentId) {
      //     if (item.children && item.children.length > 0) {
      //       item.children.push(addItem);
      //     } else {
      //       this.$set(item, "children", [addItem]);
      //     }
      //   } else if (item.children) {
      //     for (let i of item.children) {
      //       if (i.id === parentId) {
      //         if (i.children && i.children.length > 0) {
      //           i.children.push(addItem);
      //         } else {
      //           this.$set(i, "children", [addItem]);
      //         }
      //       }
      //     }
      //   }
      // }
      if (this.addItemToTree(this.tableData, parentId, addItem)) {
        console.log("看看组合后的数据", this.tableData);
        this.$nextTick(() => {
          this.$refs.tree._initTree(this.tableData);
          this.optionTreeFn();
        });
      }
    },
    addItemToTree(tableData, parentId, addItem) {
      for (let item of tableData) {
        // 查找匹配的 parentId
        if (item.id === parentId) {
          // 检查是否有 children
          if (item.children && item.children.length > 0) {
            // 如果有 children，直接推入新项
            item.children.push(addItem);
          } else {
            // 如果没有 children，初始化一个 children 数组
            this.$set(item, "children", [addItem]);
          }
          return true; // 找到并添加后返回
        }

        // 如果当前节点有 children，递归查找
        if (item.children) {
          const found = this.addItemToTree(item.children, parentId, addItem);
          if (found) {
            return true; // 如果在子节点中找到，返回
          }
        }
      }
      return false; // 没有找到，返回 false
    },
    // 删除章节的方法
    delFn(id) {
      console.log("看看这个id", id);
      // 处理后端返回的数据id 删除对应章节
      this.$request({
        url: "/knowledgeFile/video/deleteChapter",
        method: "post",
        data: {
          id,
        },
      }).then((data) => {
        // this.$toast("删除成功")
        this.tableData[0].children.forEach((item, index) => {
          if (item.id === id) {
            this.tableData[0].children.splice(index, 1);
          } else if (item.children) {
            item.children.forEach((i, index) => {
              if (i.id === id) {
                item.children.splice(index, 1);
              }
            });
          }
        });
        this.$refs.tree._initTree(this.tableData);
        this.optionTreeFn();
      });
    },
    // 修改名称
    editNameFn(item, id) {
      console.log(item, this.tableData, id, "fffff");

      this.tableData = this.updateNodeName(this.tableData, id, item.folderName);
      console.log(this.tableData, "666");
      this.optionTreeFn();
    },
    //视频播放
    handlePlayer(row) {
      console.log(row, "视频播放");
      if (row.videoType === 1) {
        this.$tab.navigateTo(`/pages/player?info=${encodeURIComponent(JSON.stringify(row))}&showCollects=false`);
      } else {
        this.$tab.navigateTo(`/pages/preview?info=${encodeURIComponent(JSON.stringify(row))}&showCollects=false`);
      }
    },
    updateNodeName(data, targetId, newName) {
      return data.map((node) => {
        if (node.id === targetId) {
          return { ...node, chapterName: newName };
        }
        if (node.children) {
          return { ...node, children: this.updateNodeName(node.children, targetId, newName) };
        }

        return node;
      });
    },
    handleFileInfo(row) {
      this.$tab.navigateTo(`/pages/fileManage/fileInfo?item=${encodeURIComponent(JSON.stringify(row))}`);
    },
    // 递归操作数据
    chapterFn(chapter) {
      console.log("看看匹配的id", chapter);
      const recursiveSearch = (nodes) => {
        for (const node of nodes) {
          // 检查当前节点的 videoList
          if (node.videoList) {
            // node.videoList.find( item => item.chapter == chapter)
            // return node.videoList; // 找到匹配的 chapterId
            const index = node.videoList.findIndex((item) => (item.id || item.chapter) === chapter);
            if (index !== -1) {
              // 找到匹配的 chapter ID，删除对应的数据
              const delteData = JSON.parse(JSON.stringify(node.videoList[index]));
              setTimeout(() => {
                node.videoList.splice(index, 1);
              }, 200);
              return { deleted: true, item: delteData }; // 返回删除成功的信息
            }
          }

          // 如果有 children，递归搜索 children
          // if (node.source && node.source.children) {
          //   const result = recursiveSearch(node.source.children);
          //   if (result && result.deleted) {
          //     return result; // 如果在 children 中找到，返回 true
          //   }
          // }

          if (node && node.children) {
            const result = recursiveSearch(node.children);
            if (result && result.deleted) {
              return result; // 如果在 children 中找到，返回 true
            }
          }
        }
        return null; // 没有找到，返回 false
      };
      // 开始搜索
      return recursiveSearch(this.tableData);
    },
    handleDel(row) {
      // row 当前需要处理的数据
      // 判断当前有 id参数时  为更新操作 没有就是新创建操作
      let isDel = true;
      let firstLevel = false;
      console.log(row, this.tableData, "查看详情");

      const { item } = this.chapterFn(row.id || row.chapter);
      console.log("ffffgggg", item);
      // 这里判断如果有id 走删除接口 负责只走本地删除
      if (this.id) {
        this.$request({
          url: "/knowledgeFile/file/delete",
          method: "post",
          data: {
            id: item.id,
          },
        }).then((data) => {
          if (data.code == 200) {
            this.$toast(`${item.statusName == '已入库' ? '已提交删除申请' : '删除成功'}`);
          }
          if (data.code == 1000) {
            this.$toast(data.msg);
          } else {
          }
        });
      }
      this.$refs.tree._initTree(this.tableData);
      // 需要判断是否更新  有id走更新操作
       if (this.id) {
        this.sureFn();
      }
      return;
      if (this.tableData && this.tableData[0].videoList && this.tableData[0].videoList.length > 0) {
        this.tableData[0].videoList.forEach((item, index) => {
          if (row.chapter === item.chapter) {
            firstLevel = true;
            // this.tableData[0].videoList.splice(index, 1)
            if (this.tableData[0].videoList[index].id) {
              this.$request({
                url: "/knowledgeFile/file/delete",
                method: "post",
                data: {
                  id: this.tableData[0].videoList[index].id,
                },
              }).then(({ data }) => {
                if (data.code == 1000) {
                  this.$toast(data.msg);
                  isDel = false;
                } else {
                }
              });
            }
            setTimeout(() => {
              if (isDel) {
                this.tableData[0].videoList.splice(index, 1);
              }
            }, 1000);
          }
        });
      }
      if (!firstLevel) {
        this.tableData[0].children.forEach((item, index) => {
          let flag = false;
          if (item.videoList && item.videoList.length > 0) {
            item.videoList.forEach((temp, tIndex) => {
              if (temp.chapter === row.chapter) {
                // this.tableData[0].children[index].videoList.splice(tIndex, 1)
                if (this.tableData[0].children[index].videoList[tIndex].id) {
                  this.$request({
                    url: "/knowledgeFile/file/delete",
                    method: "post",
                    data: {
                      id: this.tableData[0].children[index].videoList[tIndex].id,
                    },
                  }).then(({ data }) => {});
                }
                this.tableData[0].children[index].videoList.splice(tIndex, 1);
                flag = true;
              }
            });
          }
          if (flag) {
            return true;
          }
          if (item.children && item.children.length > 0) {
            item.children.forEach((child, cIndex) => {
              if (child.videoList && child.videoList.length > 0) {
                child.videoList.forEach((temp, tIndex) => {
                  if (temp.chapter === row.chapter) {
                    // this.tableData[0].children[index].children[cIndex].videoList.splice(tIndex, 1)
                    if (this.tableData[0].children[index].children[cIndex].videoList[tIndex].id) {
                      this.$request({
                        url: "/knowledgeFile/file/delete",
                        method: "post",
                        data: {
                          id: this.tableData[0].children[index].children[cIndex].videoList[tIndex].id,
                        },
                      }).then(({ data }) => {});
                    }
                    this.tableData[0].children[index].children[cIndex].videoList.splice(tIndex, 1);
                  }
                });
              }
            });
          }
        });
      }
      this.$refs.tree._initTree(this.tableData);

      // 需要判断是否更新  有id走更新操作
      if (this.id) {
        this.sureFn();
      }
    },
    closeModel() {
      this.updateModel = false;
      console.log("4444");
    },
    confirm() {
      this.operationIndex = -1;
      this.updateModel = false;
      this.updateShow = true;
    },
    handleUpdate(parentRow, row) {
      this.updateData = JSON.parse(JSON.stringify(row));
      this.parentRow = parentRow;
      this.updateProcessList = {}
      console.log(row, "rowrowrow");
      this.isUpload = false
      if (row && row.status == 5) {
        // 模态框提示
        this.updateModel = true;
        return;
      }
      this.updateShow = true
    },
    //视频更新
    handleUpdate1(parentRow, row) {
      let fileType = this.updateData.fileName.substring(this.updateData.fileName.lastIndexOf(".") + 1).toLowerCase();
      let that = this;
      if (fileType !== "ppt" && fileType !== "pptx" && fileType !== "pdf") {
        uni.chooseVideo({
          sourceType: ["camera", "album"],
          success: function (res) {
              if (res.size > 3 * 1024 * 1024 * 1024) {//3GB
                  that.$toast("仅支持大小为3GB以内的文件");
                  return;
              }
            self.src = res.tempFilePath;
            that.loading++;
            uni.uploadFile({
              url: config.baseUrl + "/file/upload",
              header: {
                token: that.token,
              },
              filePath: res.tempFilePath,
              name: "file",
              formData: {
                fileType: that.course.fileType,
                profession: that.course.profession,
              },
              // 开始假进度条
              beforeSend: () => {
                const file = res.tempFiles[0];
                that.startFakeProgress(file);
              },
              success: (uploadFileRes) => {
                that.loading--;
                let tempData = JSON.parse(uploadFileRes.data);
                if (tempData.data.uploadStatus === 1) {
                  that.$toast("文件名重复，不可导入！");
                that.stopFakeProgress();
                return;
              }
                that.updateProcessList = tempData.data
                // 更新文件需要替换id 新上传的id替换旧id
                that.updateData.fileId = tempData.data.id;
                that.updateData.fileName = tempData.data.fileName;
                that.uploadFileId = tempData.data.id;
                console.log(that.parentRow.videoList, tempData, that.tableData, row, "that.updateData.videoList");
                /*that.parentRow.videoList = that.parentRow.videoList.filter(item => item.id !== that.updateData.id)
                              that.parentRow.videoList.push({
                                  ...tempData.data,
                                  chapter: tempData.data.id || Date.now()
                              })*/
                that.updateNodeInTree(that.tableData, that.parentRow.id, that.parentRow);
                console.log('that.updateData.id', that.updateData)
                that.updateFileNameInTree(that.tableData, that.updateData.id, that.updateData.fileName)
                console.log('----that.updateData.id', that.updateData)

                this.id = tempData.data.id;
                // that.sureFn(tempData.data.id);
                that.$forceUpdate();
              },
              fail: (uploadFileError) => {
                // 处理上传失败的错误
                that.loading--;
              },
            });
          },
        });
      } else {
        console.log("更新文件");
        uni.chooseFile({
          count: 1, //默认100
          extension: [".ppt", ".pptx", ".pdf"],
          success: function (res) {
    
              if (res.tempFiles && res.tempFiles.length > 0 && res.tempFiles[0].size > 2 * 1024 * 1024 * 1024) {//1GB
                  that.$toast("仅支持大小为1GB以内的文件");
                  return;
              }
              console.log(23333,res)
            that.loading++;
            uni.uploadFile({
              url: config.baseUrl + "/file/upload",
              header: {
                token: that.token,
              },
              filePath: res.tempFilePaths[0],
              name: "file",
              formData: {
                fileType: that.course.fileType,
                profession: that.course.profession,
              },
              success: (uploadFileRes) => {
                that.loading--;
                let tempData = JSON.parse(uploadFileRes.data);
                if (tempData.data.uploadStatus === 1) {
                  that.$toast("文件名重复，不可导入！");

                  return;
                }
                that.updateProcessList = tempData.data
                that.uploadFileId = tempData.data.id;
                console.log(that.parentRow.videoList, "that.updateData.videoList");
                // 更新文件需要替换id 新上传的id替换旧id
                that.updateData.fileId = tempData.data.id;
                /*that.parentRow.videoList = that.parentRow.videoList.filter(item => item.id !== that.updateData.id)
                              that.parentRow.videoList.push({
                                  ...tempData.data,
                                  chapter: tempData.data.id || Date.now()
                              })*/
                that.updateNodeInTree(that.tableData, that.parentRow.id, that.parentRow);
                that.updateFileNameInTree(that.tableData, that.updateData.id, that.updateData.fileName)
                this.id = tempData.data.id;
                // that.sureFn(tempData.data.id);
                that.$forceUpdate();
              },
              fail: (uploadFileError) => {
                // 处理上传失败的错误
                that.loading--;
              },
            });
          },
        });
      }
    },
    // 递归更新 tree 中的 fileName
    updateFileNameInTree(treeList, fileId, newFileName) {
      console.log(treeList, fileId, newFileName)
      if (!treeList || !treeList.length) {
        return;
      }
      for (let i = 0; i < treeList.length; i++) {
        if (treeList[i].videoList) {
          for (let j = 0; j < treeList[i].videoList.length; j++) {
            if (treeList[i].videoList[j].id === fileId) {
              this.$set(treeList[i].videoList[j], 'fileName', newFileName);
              this.$set(treeList[i].videoList[j], 'fileId', this.uploadFileId)
              // uploadFileId
              return;
            }
          }
        }
        this.updateFileNameInTree(treeList[i].children, fileId, newFileName);
      }
    },
    uploadVideofile(row, tempData) {
      console.log(row, tempData)
      if (row && row.videoList && row.videoList.length > 0) {
      } else {
        this.$set(row, "videoList", []);
      }
      row.videoList.push({
        ...tempData,
        videoType: 0,
        chapter: tempData.id || Date.now(),
      });
      console.log(this.tableData, row.id, row)
      this.updateNodeInTree(this.tableData, row.id, row);
      this.optionTreeFn();
      this.isUpload = true
    },
    uploadVideo(row, fileType) {
      this.isUpload = true
      let that = this;
      console.log("看看这里能不能加判断", row, fileType, this.tableData);
      // 之前旧代码中没有根据文件类型区分开存放 这里需要过滤类型判断数量
      // if (row.videoList && fileType == "video") {
      //   const result = row.videoList ? row.videoList.find((H) => ["mp4", "mov","avi", "wmv"].includes(H.fileFormat)) : '';
      //   if (result) {
      //     this.$toast("当前目录只能上传一个视频文件");
      //     return;
      //   }
      // }
      // if (row.videoList && fileType == "ppt") {
      //   const result = row.videoList.find((H) => ["ppt", "pptx","pdf"].includes(H.fileFormat));
      //   if (result) {
      //     this.$toast("当前目录只能上传一个课程文件");
      //     return;
      //   }
      // }

      if (fileType === "video") {
        uni.chooseVideo({
          sourceType: ["camera", "album"],
          success: function (res) {
              if (res.size > 3 * 1024 * 1024 * 1024) {//3GB
                  that.$toast("仅支持大小为3GB以内的文件");
                  return;
              }
              console.log(res, 'res33')
            // that.loading++;
            that.progress = 0
            that.progressVisible = true
            that.currentFileName = res.name || ''
            self.src = res.tempFilePath;
            
            // 实现基于文件大小的假进度条
            const file = res;
            that.startFakeProgress(file);
            
            uni.uploadFile({
              url: config.baseUrl + "/knowledgeFile/video/upload",
              header: {
                token: that.token,
              },
              filePath: res.tempFilePath,
              name: "file",
              formData: {
                fileType: that.course.fileType,
                profession: that.course.profession,
              },
              success: (uploadFileRes) => {
              console.log(uploadFileRes, 'uploadFileRes2222')
            that.loading--;
            // 先停止假进度条
            that.stopFakeProgress();
            // 设置进度为100%
            that.progress = 100;
            // 延迟300毫秒后再隐藏进度条，让用户能看到100%的状态
            setTimeout(() => {
              that.progressVisible = false;
            }, 300);

                let tempData = JSON.parse(uploadFileRes.data);
                if (!["avi", "mp4", "wmv", "mov"].includes(tempData.data.fileFormat)) {
                  that.$toast("仅支持.avi .mp4 .wmv .mov格式文件");
                  return;
                }
                if (tempData.data.uploadStatus === 1) {
                  that.$toast("文件名重复，不可导入！");
                  return;
                }
                if (row && row.videoList && row.videoList.length > 0) {
                } else {
                  that.$set(row, "videoList", []);
                }
                row.videoList.push({
                  ...tempData.data,
                  videoType: 1,
                  chapter: tempData.data.id || Date.now(),
                });
                that.updateNodeInTree(that.tableData, row.id, row);
                that.optionTreeFn();
              },
              fail: (uploadFileError) => {
                // 处理上传失败的错误
                that.loading--;
                // 先停止假进度条
                that.stopFakeProgress();
                // 设置进度为100%（即使失败也显示完成状态）
                that.progress = 100;
                // 延迟300毫秒后再隐藏进度条
                setTimeout(() => {
                  that.progressVisible = false;
                }, 300);
              },
            });
          },
        });
      } else {
        uni.chooseFile({
          count: 1, //默认100
          extension: [".ppt", ".pptx", ".pdf"],
          success: function (res) {
              if (res.tempFiles && res.tempFiles.length > 0 && res.tempFiles[0].size > 2 * 1024 * 1024 * 1024) {//1GB
                  that.$toast("仅支持大小为1GB以内的文件");
                  return;
              }
            uni.uploadFile({
              url: config.baseUrl + "/knowledgeFile/video/upload",
              header: {
                token: that.token,
              },
              filePath: res.tempFilePaths[0],
              name: "file",
              formData: {
                fileType: that.course.fileType,
                profession: that.course.profession,
              },
              success: (uploadFileRes) => {
                let tempData = JSON.parse(uploadFileRes.data);
                console.log("ffff", tempData);
                if (!["ppt", "pptx","pdf"].includes(tempData.data.fileFormat)) {
                  that.$toast("仅支持.ppt，.pptx，.pdf格式文件");
                  return;
                }
                if (tempData.data.uploadStatus === 1) {
                  that.$toast("文件名重复，不可导入！");
                  return;
                }
                if (row && row.videoList && row.videoList.length > 0) {
                } else {
                  that.$set(row, "videoList", []);
                }
                row.videoList.push({
                  ...tempData.data,
                  videoType: 0,
                  chapter: tempData.data.id || Date.now(),
                });
                that.updateNodeInTree(that.tableData, row.id, row);
                that.optionTreeFn();
              },
              fail: (uploadFileError) => {
                // 处理上传失败的错误
                that.stopFakeProgress();
              },
            });
          },
        });
      }
    },
    //通过id找到对应的节点，将obj挂在该节点上
    updateNodeInTree(treeList, id, obj) {
      if (!treeList || !treeList.length) {
        return;
      }
      for (let i = 0; i < treeList.length; i++) {
        if (treeList[i].id === id) {
          // treeList[i] = obj
          treeList[i] = {
            ...treeList[i],
            ...obj,
          };
          break;
        }
        this.updateNodeInTree(treeList[i].children, id, obj);
      }
    },
    // 开始假进度条
    startFakeProgress(file) {
      console.log("🚀 ~ fi----le:", file)
      this.stopFakeProgress(); // 先清除之前的定时器
      
      // 根据文件大小动态计算动画时间（基于实际测试数据）
      const fileSize = file.size || 0;
      
      // 基于测试数据的计算：300MB约需2分钟(120000毫秒)
      // 计算上传速度基准：300MB / 120000ms = 0.0025 MB/ms
      const baseUploadSpeed = 0.0016; // MB/ms
      
      // 计算文件大小（MB）
      const fileSizeMB = fileSize / (1024 * 1024);
      
      // 基础时间计算
      let totalTime = fileSizeMB / baseUploadSpeed;
      
      // 确保小文件有合理的最小时间（至少3秒）
      totalTime = Math.max(totalTime, 3000);
      
      // 针对中文件的微调（10-50MB）- 基于13MB约20秒的测试数据
      if (fileSizeMB > 10 && fileSizeMB <= 50) {
        // 线性调整，确保13MB文件显示约20秒
        const adjustmentFactor = 0.8;
        totalTime = totalTime * adjustmentFactor;
      }
      
      // 对于超大文件（>2GB），应用递减因子避免时间过长
      if (fileSizeMB > 2000) {
        // 随着文件变大，时间增长逐渐放缓
        const largeFileFactor = 0.9 + (fileSizeMB / 10000); // 最大约1.1的因子
        totalTime = totalTime * largeFileFactor;
      }
      
      // 添加一些随机波动，让进度看起来更自然（±5%）
      const randomFactor = 0.95 + Math.random() * 0.1;
      totalTime = totalTime * randomFactor;
      
      // 计算每100ms增加的进度
      const progressIncrement = 100 / (totalTime / 100);
      let currentProgress = 0;
      
      // 设置定时器更新进度
      this.progressTimer = setInterval(() => {
        currentProgress += progressIncrement;
        
        // 确保进度不会超过99%（真实上传完成后会设为100%）
        if (currentProgress >= 99) {
          currentProgress = 99;
          clearInterval(this.progressTimer);
        }
        
        this.progress = Math.round(currentProgress);
        console.log("🚀 ~ this.progress:", this.progress)
      }, 100);
    },
    
    // 停止假进度条
    stopFakeProgress() {
      if (this.progressTimer) {
        clearInterval(this.progressTimer);
        this.progressTimer = null;
      }
    },
    
    closeFn() {
      uni.navigateBack({
        delta: 1,
      });
      this.emptyFn();
    },
    emptyFn() {
      this.tableData = [];
      this.course.folderName = "";
      this.course.author = "";
      this.course.introduction = "";
      this.stopFakeProgress();
    },
    traverseTree(data) {
      if (!data) return;

      for (let i = 0; i < data.length; i++) {
        // 处理当前节点
        if (data[i].parentId && typeof data[i].parentId !== "string" && typeof data[i].parentId !== "number") {
          /*data[i].parentId = data[i].parentId.map(item => {
							    return item
							}).join(',')*/
          if (data[i].parentId && data[i].parentId.length > 0) {
            data[i].parentId = data[i].parentId[data[i].parentId.length - 1];
          } else {
            data[i].parentId = null;
          }
        }
        // 递归遍历子节点
        this.traverseTree(data[i].children);
      }
    },
    treeForeach(tree) {
      tree.forEach((data) => {
        if (data.isEdit) {
          delete data.id;
        }
        data.children && this.treeForeach(data.children);
      });
    },
    updateConfirm() {
      console.log('sureFn', this.course)
      if(this.course.folderName == ""){
        this.$toast(this.methods == 'videoUpdate' ? "正在加载中" : "课程名称不能为空")
        return
      }
      if(this.course.author == ""){
        this.$toast("作者名称不能为空")
        return
      }
      if(this.course.introduction == ""){
        this.$toast("课程简介不能为空")
        return
      }
      console.log("查看更新节点", this.tableData);
      //修改parentId为字符串
      this.traverseTree(this.tableData);
      //编辑时新增节点不需要id属性
      this.treeForeach(this.tableData);
      if (!this.isUpload) {
        this.updateFileNameInTree(this.tableData, this.updateData.id, this.updateData.fileName)
      }
      this.$request({
        url: "/knowledgeFile/file/update",
        method: "post",
        data: {
          fileType: this.updateData.fileType,
          profession: this.updateData.profession,
          fileName: this.updateData.fileName,
          fileId: this.uploadFileId,
          id: this.updateData.id
        },
      }).then((data) => {
        if (data.code === 200) {
           this.$toast("更新成功")
          uni.$emit("returnData");
          // 这里是更新接口 需要更新完后再获取一次当前数据
          this.updateStatus = false;
          this.updateShow = false;
          this.getInfo();
        } else {
          this.$modal.loading("编辑异常，请重试！");
          setTimeout(() => {
            this.$modal.closeLoading();
          }, 1000);
        }
      });
      
    },
    // 更新和新增按钮公用一个方法
    sureFn() {
      console.log('sureFn', this.course)
      if(this.course.folderName == ""){
        this.$toast(this.methods == 'videoUpdate' ? "正在加载中" : "课程名称不能为空")
        return
      }
      if(this.course.author == ""){
        this.$toast("作者名称不能为空")
        return
      }
      if(this.course.introduction == ""){
        this.$toast("课程简介不能为空")
        return
      }
      console.log("查看更新节点", this.tableData);
      //修改parentId为字符串
      this.traverseTree(this.tableData);
      if (this.id) {
        //编辑时新增节点不需要id属性
        this.treeForeach(this.tableData);
        if (!this.isUpload) {
          this.updateFileNameInTree(this.tableData, this.updateData.id, this.updateData.fileName)
        }
        this.$request({
          url: "/knowledgeFile/video/update",
          method: "post",
          data: {
            course: {
              ...this.course,
              id: this.id,
            },
            video: this.tableData[0],
          },
        }).then((data) => {
          if (data.code === 200) {
            //  this.$toast("更新成功")
            // uni.$emit('returnData', this.processList)
            uni.$emit("returnData");
            // setTimeout(function () {
            //   uni.navigateBack();
            // }, 1000);
            // this.getInfo();
            // 这里是更新接口 需要更新完后再获取一次当前数据
            this.updateStatus = false;
            this.updateShow = false;
            this.getInfo();
          } else {
            this.$modal.loading("编辑异常，请重试！");
            setTimeout(() => {
              this.$modal.closeLoading();
            }, 1000);
          }
        });
      } else {
        this.$request({
          url: "/knowledgeFile/video/save",
          method: "post",
          data: {
            course: {
              ...this.course,
            },
            video: this.tableData[0],
          },
        }).then((data) => {
          if (data.code === 200) {
            this.$modal.loading("导入成功！");
            setTimeout(() => {
              this.$modal.closeLoading();
            }, 1000);
            // uni.$emit('returnData', this.processList)
            uni.$emit("returnData");
            setTimeout(function () {
              uni.navigateBack();
            }, 1000);
          } else {
            this.$modal.loading("导入异常，请重试！");
            setTimeout(() => {
              this.$modal.closeLoading();
            }, 1000);
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  height: calc(100vh - 230rpx);
  padding: 32rpx 30rpx 0;
  overflow: auto;

  .upload_type {
    min-height: 100rpx;
    border-radius: 16rpx;
    background: #ffffff;
    width: 100%;
    display: grid;
    grid-template-columns: 160rpx 1fr;
    grid-template-gap: 30rpx;
    align-items: center;
    padding: 30rpx;
    font-family: 思源黑体;
    font-size: 30rpx;
    color: #1c2126;
    text ::before{
      content: "*";
      color: red;
      padding-right: 10rpx;
    }
    text{
      // padding-right: 20px;
    }
    & + .upload_type {
      margin-top: 20rpx;
    }
    ::v-deep {
      .u-input__content__field-wrapper__field {
        text-align: right !important;
        color: #4c5a67 !important;
        font-size: 30rpx !important;
      }
      .u-input,
      .u-textarea {
        border: none;
        background: #ffffff !important;
      }
    }
    &.upload_type_introduction {
      grid-template-columns: 1fr;
      grid-row-gap: 20rpx;
      ::v-deep {
        .u-textarea {
          padding: 0;
        }
        .u-textarea__field {
          font-family: Source Han Sans;
          font-size: 30rpx;
          color: #1c2126;
        }
      }
    }
  }

  .bottom {
    width: 100%;
    display: flex;
    justify-content: space-between;
    position: absolute;
    bottom: 32rpx;
    left: 0;
    height: 80rpx;
    padding: 0 30rpx;
    border-radius: 16px;
    ::v-deep .u-button {
      width: 100%;
      font-family: Poppins;
      font-size: 32rpx;
      height: 80rpx;
      & + .u-button {
        margin-left: 30rpx;
      }
    }
  }

  .video_model {
    border-radius: 16rpx;
    background: #ffffff;
    margin-top: 40rpx;
    padding: 30rpx 30rpx 80rpx;
    .video_model_title {
      display: grid;
      grid-template-columns: 36rpx 1fr;
      grid-column-gap: 20rpx;
      font-family: Source Han Sans;
      font-size: 32rpx;
      font-weight: 500;
      color: #1c2126;
      image {
        width: 36rpx;
        height: 34rpx;
      }
    }
  }
  .container-update {
    padding: 20rpx 50rpx;
    height: max-content;

    .info_item {
      display: flex;
      // height: 60rpx;
      line-height: 60rpx;
      margin: 20rpx 0;

      .info_item_label {
        width: 160rpx;
      }

      .info_item_content {
        flex: 1;
      }
    }

    .confrim-btn {
      width: 100%;
      display: flex;
      justify-content: space-between;

      .u-button {
        width: 40%;
      }
    }
  }
  .fileUpload {
    position: fixed;
    bottom: 110rpx;
    width: calc(100% - 40rpx);
    margin-left: 20rpx;
    z-index: 100;
    font-size: 32rpx;
    font-family: Poppins;
    font-weight: 600;
    height: 100rpx;
    border-radius: 16rpx;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    background: #0084ff;
  }
  /* 蒙版进度条样式 */
    .progress-mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }
    
    .progress-content {
        background-color: white;
        border-radius: 20rpx;
        padding: 60rpx 40rpx;
        width: 600rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
    }
    
    .circle-progress-container {
        position: relative;
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 40rpx;
    }
    
    .circle-progress {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background: conic-gradient(#007AFF var(--progress-deg), #E8F0FE var(--progress-deg));
        display: flex;
        justify-content: center;
        align-items: center;
        transition: background 0.3s ease;
    }
    
    .progress-inner {
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
        background-color: white;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        box-shadow: inset 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }
    
    .loading-icon {
        animation: spin 1s linear infinite;
    }
    
    .progress-text {
        font-size: 32rpx;
        font-weight: 600;
        color: #007AFF;
        margin-top: 10rpx;
    }
    
    .upload-info {
        text-align: center;
    }
    
    .upload-text {
        font-size: 34rpx;
        font-weight: 500;
        color: #1C2126;
        margin-bottom: 20rpx;
    }
    
    .file-name {
        font-size: 28rpx;
        color: #4C5A67;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
    
    /* 蒙版进度条样式 */
    .progress-mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }
    
    .progress-content {
        background-color: white;
        border-radius: 20rpx;
        padding: 60rpx 40rpx;
        width: 600rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
    }
    
    .circle-progress-container {
        position: relative;
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 40rpx;
    }
    
    .circle-progress {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background: conic-gradient(#007AFF var(--progress-deg), #E8F0FE var(--progress-deg));
        display: flex;
        justify-content: center;
        align-items: center;
        transition: background 0.3s ease;
    }
    
    .progress-inner {
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
        background-color: white;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        box-shadow: inset 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }
    
    .loading-icon {
        animation: spin 1s linear infinite;
    }
    
    .progress-text {
        font-size: 32rpx;
        font-weight: 600;
        color: #007AFF;
        margin-top: 10rpx;
    }
    
    .upload-info {
        text-align: center;
    }
    
    .upload-text {
        font-size: 34rpx;
        font-weight: 500;
        color: #1C2126;
        margin-bottom: 20rpx;
    }
    
    .file-name {
        font-size: 28rpx;
        color: #4C5A67;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
}
</style>
